package com.nx.platform.es.bean.modle.sort;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;
import org.elasticsearch.common.Strings;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author
 * @since 2016年10月15日
 */
public class FieldSortParser implements SortFieldConfigParser {

    private static final Pattern FORMAT = Pattern.compile("[\\w.]++");

    @Override
    public ImmutableMap<String, ?> parse(Map<?, ?> settings) {
        String fieldName = MoreMaps.getString(settings, "fieldName", "");
        Preconditions.checkState(FORMAT.matcher(fieldName).matches(), "param fieldName empty or incorrect");
        String order = MoreMaps.getString(settings, "order");
        if (!Strings.isNullOrEmpty(order)) {
            if ("desc".equalsIgnoreCase(order)) {
                return ImmutableMap.of("fieldName", fieldName, "order", SortOrder.DESC);
            } else if ("asc".equalsIgnoreCase(order)) {
                return ImmutableMap.of("fieldName", fieldName, "order", SortOrder.ASC);
            }
        }
        return ImmutableMap.of("fieldName", fieldName);
    }

}
